<?php
/**
 * Created by PhpStorm.
 * User: 共赢岛
 * Date: 2024/1/12
 * Time: 13:53
 */

namespace App\Services\LifeCycle;


use App\Models\Department;
use Illuminate\Support\Facades\Auth;

class DepartmentService
{
    public static function all($condition = [])
    {
        return Department::where($condition)->get();
    }

    public static function storeSelect()
    {
        $new_store = [];

        $store = StoreService::all();

        if ($store) {
            foreach ($store as $key => $value) {
                $children = [];

                $new_store[$key]['value'] = $value['id'];
                $new_store[$key]['text'] = $value['title'];
                $department = self::all(['store_id' => $value['id']]);

                if ($department) {
                    foreach ($department as $k => $v) {
                        $children[$k]['text'] = $v['title'];
                        $children[$k]['value'] = '-'.$v['id'];
                    }
                }

                $new_store[$key]['children'] = $children;
            }
        }

        return $new_store;
    }

    public static function save($param = [])
    {
        $user = Auth::user();

        $department_ids = explode('-', $param['department_id']);

        if ($department_ids[0] == '') {
            $department_id = $department_ids[1];
        } else {
            $department_id = $department_ids[0];
        }

        $user->store_id = $param['store_id'];
        $user->department_id = $department_id;
        $user->name = $param['name'];
        $user->phone = $param['phone'];
        $user->type = MEMBER_TYPE_STAFF;

        $user->save();

        return true;
    }
}